package com
import (
	"os"
    "fmt"
    "encoding/json"
	jwt "github.com/dgrijalva/jwt-go"
	"net/http"
	"github.com/bugfan/logrus"    	
	_ "github.com/bugfan/logrus/hooks/file"
	"github.com/bugfan/to"	
)


func MiddlewareHandler(next http.Handler) http.Handler{
    return http.HandlerFunc(func(w http.ResponseWriter,r *http.Request){
		logrus.Info("请求 url: ",r.URL.Path,r.URL.Query().Get("token"))
		if !CheckToken(r.URL.Query().Get("token"),""){
			return
		}
        next.ServeHTTP(w,r)
    })
}
func CheckToken(token,e string)bool{
	if to.Bool(os.Getenv("DebugAuth")){
		return true
	}
	return DecodeJWT(token,e)	
}
func DecodeJWT(token,auth string) bool{
	if len(token)<5{
		fmt.Println("token长度不足5个")		
		return false
	}
	mySigningKey := []byte(os.Getenv("Secret"))
    t, err := jwt.Parse(token[4:], func(*jwt.Token) (interface{}, error) {
        return mySigningKey, nil
    })
    if err != nil {
        fmt.Println("parase with claims failed.", err)
        return false
    }
	// fmt.Println("还原后的token信息claims部分:", t.Claims)
	if auth==""{		//读权限
		return true
	}
	bs,_:=json.Marshal(t.Claims)
	newS:=myMarshal(bs)
	for _,v:=range newS{
		fmt.Println("case auth:",v)
		if v==auth{
			return true
		}
	}
	return false
}
type MyJWTStruct struct{
	User_id string `json:"user_id"`
	Username string `json:"username"`
	Exp		float64 `json:"exp"`
	Email 	string `json:"email"`
	Orig_iat float64 `json:"orig_iat"`
	Modules []string `json:"modules"`
}
func myMarshal(bs []byte) []string{
	obj:=MyJWTStruct{}
	json.Unmarshal(bs,&obj)
	fmt.Println("全部数据打印:",obj)
	return obj.Modules
}